package com.lmbsvn.core.shiro.helper;

import com.google.code.kaptcha.Constants;
import com.lmbsvn.core.util.Config;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import java.util.Collection;

public class ShiroSecurityHelper {
	/**
	 * 通过用户名获得 Session对象
	 * @param username
	 * @return
	 */
	public static Session getSessionByUsername(SessionDAO sessionDAO, String username){
		Collection<Session> sessions = sessionDAO.getActiveSessions();
		for(Session session : sessions){
			if(null != session && StringUtils.equals(String.valueOf(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)), username)){
				return session;
			}
		}
		return null;
	}
	
	/**
	 * 踢出用户
	 * @param session
	 */
	public static void kickOutUser(Session session){
		session.removeAttribute(Config.LOGININFO);
		session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
		session.setAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY, false);
		session.setAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY, null);
	}
	
	/**
	 * 用户登录成功，将用户信息放到session里
	 * @param obj
	 */
	public static void setUserToSession(Session session, Object obj){
		if(null != session){
			session.setAttribute(Config.LOGININFO, obj);
		}
	}
}
